package com.example.kleinanzeigengenerator.listview;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.kleinanzeigengenerator.R;
import com.example.kleinanzeigengenerator.common.Constants;

public class EbayListActivity extends ListActivity{
	private static EbayActivate ebayInvoke;
	private static EbayParser ebayParser;
	private static ProgressDialog progressDialog;
	private String searchTerm;
	private SearchResult listings;
	private ListingArrayAdapter adapter;;
	private Listing selectedListing;
	private int selectedPosition;
	private AlertDialog listingDetailDialog;
	private ImageView imageViewImage;
	private TextView textViewStartTime;
	private TextView textViewEndTime;
	private TextView textViewListingType;
	private TextView textViewPrice;
	private TextView textViewShipping;
	private TextView textViewLocation;
	private TextView textViewLink;
	private AlertDialog keywordDialog;
	private EditText keywordTextbox;
	private final static int MENU_KEYWORD=0;


	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		
		Intent i = getIntent();
		searchTerm = i.getStringExtra(Constants.SEARCH_TERM_TAG);
		
		try{
			ListView listView=this.getListView();
			listView.setTextFilterEnabled(true);
			listView.setOnItemClickListener(selectItemListener);
		}catch(Exception x){
			Log.e(Constants.EBAY_LISTACTIVITY_TAG,"onCreate",x);
			this.showErrorDialog(x);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		try{
			menu.add(0,MENU_KEYWORD,0,"Suche");
			menu.add(0,Constants.MENU_QUIT_TAG,1,"Ausgang");
			return(true);
		}catch(Exception x){
			Log.e(Constants.EBAY_LISTACTIVITY_TAG,"onCreateOptionsMenu",x);
			return(false);
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		try{
			switch(item.getItemId()){
			case MENU_KEYWORD:{this.showKeywordDialog();return(true);}
			case Constants.MENU_QUIT_TAG:{this.finish();return(true);}
			default:{return(false);}
			}
		}catch(Exception x){
			Log.e(Constants.EBAY_LISTACTIVITY_TAG,"onOptionsItemSelected",x);
			return(false);
		}
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		if((this.listingDetailDialog!=null)&&(this.listingDetailDialog.isShowing())){
			return;
		}
		this.refreshListings();
	}
	
	OnClickListener onKeywordDialogCancelListener=new OnClickListener(){
		public void onClick(DialogInterface dialog,int which){/*TODO*/}
	};

	private void showKeywordDialog(){
		try{
			if(this.keywordDialog==null){
				LayoutInflater inflater=(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
				View layout=inflater.inflate(R.layout.searchdialog,(ViewGroup)findViewById(R.id.searchdialog_root));
				AlertDialog.Builder builder=new AlertDialog.Builder(this);
				builder.setView(layout);
				builder.setTitle("Suche");
				builder.setPositiveButton("OK",onKeywordDialogPositiveListener);
				builder.setNegativeButton("Abbruch",onKeywordDialogCancelListener);
				this.keywordTextbox=(EditText)layout.findViewById(R.id.searchdialog_keyword);
				this.keywordDialog=builder.create();
			}
			this.keywordDialog.show();
		}catch(Exception x){
			Log.e(Constants.EBAY_LISTACTIVITY_TAG,"showFilterDialog",x);
		}
	}

	
	OnClickListener onListingDetailDialogCloseListener=new OnClickListener(){
		public void onClick(DialogInterface dialog,int which){/*TODO*/}
	};	

	
	OnClickListener onKeywordDialogPositiveListener=new OnClickListener(){
		public void onClick(DialogInterface dialog,int which){
			String newSearchTerm=keywordTextbox.getText().toString().replace(" ","+");
			if(!newSearchTerm.equals(searchTerm)){
				searchTerm=newSearchTerm;
				refreshListings();
			}
		}
	};

	private void showListingDetailDialog(){
		try{

			if(this.selectedListing==null){return;}

			if(this.listingDetailDialog==null){
				LayoutInflater inflater=(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
				View layout=inflater.inflate(R.layout.listingdetail,(ViewGroup)findViewById(R.id.listingdetaildialog_root));
				AlertDialog.Builder builder=new AlertDialog.Builder(this);
				builder.setView(layout);
				builder.setTitle(this.selectedListing.getTitle());
				builder.setPositiveButton("Close",onListingDetailDialogCloseListener);
				this.imageViewImage=(ImageView)layout.findViewById(R.id.listingdetail_image);
				this.textViewStartTime=(TextView)layout.findViewById(R.id.listingdetail_starttime);
				this.textViewEndTime=(TextView)layout.findViewById(R.id.listingdetail_endtime);
				this.textViewListingType=(TextView)layout.findViewById(R.id.listingdetail_listingtype);
				this.textViewPrice=(TextView)layout.findViewById(R.id.listingdetail_price);
				this.textViewShipping=(TextView)layout.findViewById(R.id.listingdetail_shipping);
				this.textViewLocation=(TextView)layout.findViewById(R.id.listingdetail_location);
				this.textViewLink=(TextView)layout.findViewById(R.id.listingdetail_link);
				this.listingDetailDialog=builder.create();
			}

			this.textViewStartTime.setText(Html.fromHtml("<b>Start Time:</b>&nbsp;&nbsp;"+this.selectedListing.getStartTime().toLocaleString()));
			this.textViewEndTime.setText(Html.fromHtml("<b>End Time:</b>&nbsp;&nbsp;"+this.selectedListing.getEndTime().toLocaleString()));
			this.textViewPrice.setText(Html.fromHtml("<b>Price:</b>&nbsp;&nbsp;"+this.selectedListing.getCurrentPrice()));
			this.textViewShipping.setText(Html.fromHtml("<b>Shipping Cost:</b>&nbsp;&nbsp;"+this.selectedListing.getShippingCost()));
			this.textViewLocation.setText(Html.fromHtml("<b>Location</b>&nbsp;&nbsp;"+this.selectedListing.getLocation()));
			String listingType=new String("<b>Listing Type:</b>&nbsp;&nbsp;");
			if(this.selectedListing.isAuction()){
				listingType=listingType+"Auction";
				if(this.selectedListing.isBuyItNow()){
					listingType=listingType+", "+"Buy it now";
				}
			}else if(this.selectedListing.isBuyItNow()){
				listingType=listingType+"Buy it now";
			}else{
				listingType=listingType+"Not specified";
			}

			this.textViewListingType.setText(Html.fromHtml(listingType));
			StringBuffer html=new StringBuffer("<a href='");
			html.append(this.selectedListing.getListingUrl());
			html.append("'>");
			html.append("View original listing on ");
			html.append(this.selectedListing.getAuctionSource());
			html.append("</a>");
			this.textViewLink.setText(Html.fromHtml(html.toString()));
			this.textViewLink.setOnClickListener(urlClickedListener);

			this.imageViewImage.setImageDrawable(this.adapter.getImage(this.selectedPosition));

			this.listingDetailDialog.setTitle(this.selectedListing.getTitle());
			this.listingDetailDialog.show();
		}catch(Exception x){
			if((this.listingDetailDialog!=null)&&(this.listingDetailDialog.isShowing())){
				this.listingDetailDialog.dismiss();
			}
			Log.e(Constants.EBAY_LISTACTIVITY_TAG,"showListingDetailDialog",x);
		}
	}
	
	private void showErrorDialog(Exception x){
		try{
	        new AlertDialog.Builder(this)
	   		.setTitle(R.string.app_name)
	   		.setMessage(x.getMessage())
	   		.setPositiveButton("Close", null)
	   		.show();	
		}catch(Exception reallyBadTimes){
			Log.e(Constants.EBAY_LISTACTIVITY_TAG,"showErrorDialog",reallyBadTimes);
		}
	} 
	
	
	OnItemClickListener selectItemListener=new OnItemClickListener(){
		public void onItemClick(AdapterView<?> parent,View view,int position,long id){
			try{
				selectedPosition=position;
				selectedListing=(Listing)adapter.getItem(position);
				showListingDetailDialog();
			}catch(Exception x){
				Log.e(Constants.EBAY_LISTACTIVITY_TAG,"selectItemListener.onItemClick",x);
			}
		}
	};
	
	View.OnClickListener urlClickedListener=new View.OnClickListener(){
		public void onClick(View v){
			launchBrowser();
		}
	};
	
	private void launchBrowser(){
		try{
			Intent browserIntent=new Intent(Intent.ACTION_VIEW,Uri.parse(this.selectedListing.getListingUrl()));
			this.startActivity(browserIntent);
		}catch(Exception x){
			Log.e(Constants.EBAY_LISTACTIVITY_TAG,"launchBrowser",x);
			this.showErrorDialog(x);
		}
	}
	

    private final Handler loadListHandler=new Handler(){
    	public void handleMessage(Message message){
    		loadListAdapter();
    	}
	};
	
	private void loadListAdapter(){
		this.adapter=new ListingArrayAdapter(this,R.layout.listviewitem,listings);
		this.setListAdapter(this.adapter);
		if(progressDialog!=null){
			progressDialog.cancel();
		}
	}
	
	private class LoadListThread extends Thread{
        private Handler handler;
        private Context context;
        
        public LoadListThread(Handler handler,Context context){
            this.handler=handler;
            this.context=context;
        }
       
        public void run(){
        	String searchResponse="";
        	try{
        		if(ebayInvoke==null){
        			ebayInvoke=new EbayActivate(this.context);
        		}
        		if(ebayParser==null){
        			ebayParser=new EbayParser(this.context);
        		}
           		searchResponse=ebayInvoke.search(searchTerm);
           		if(listings==null){
           			listings=new SearchResult();
           		}
        		listings.setListings(ebayParser.parseListings(searchResponse));
            	this.handler.sendEmptyMessage(RESULT_OK);
        	}catch(Exception x){
    			Log.e(Constants.EBAY_LISTACTIVITY_TAG,"LoadListThread.run(): searchResponse="+searchResponse,x);
    			listings.setError(x);
    			if((progressDialog!=null)&&(progressDialog.isShowing())){
    				progressDialog.dismiss();
    			}
    			showErrorDialog(x);        		
        	}
        }
    }
	
	private void refreshListings(){
		try{
			if(progressDialog==null){
				progressDialog=new ProgressDialog(this);
			}
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("Suche Auktionen");
			progressDialog.setCancelable(false);
			progressDialog.show();
			LoadListThread loadListThread=new LoadListThread(this.loadListHandler,this.getApplicationContext());
			loadListThread.start();
		}catch(Exception x){
			Log.e(Constants.EBAY_LISTACTIVITY_TAG,"onResume",x);
			if((progressDialog!=null)&&(progressDialog.isShowing())){
				progressDialog.dismiss();
			}
			this.showErrorDialog(x);
		}	
	}

}
